lapis = require "lapis"
import respond_to from require "lapis.application"

import Model from require "lapis.db.model"

class User extends Model
    @table_name:=> "users"

class extends lapis.Application
  layout: require "views.layout"
  @enable "etlua"

  [index:"/"]: =>
        @users = User\select!
        render: true

  [user_new:"/user/new"]: respond_to{
        GET: => 
            @fields = {"name","sex","profession","age","habits","page","study","note"}
            render: true
        POST: =>
            @user = User\create {
                name: @params.name
                sex: @params.sex
                profession: @params.profession
                age: @params.age
                habits: @params.habits
                page: @params.page
                study: @params.study
                note: @params.note
            }
            @users = User\select!
            render: "index"
  }
  [user:"/user/:id"]: respond_to{
        before: =>
            @user = User\find @params.id
            @write status: 404, "Not Found" unless @user
        GET: => 
            render: true
  }

  [user_edit:"/user/edit/:id"]: respond_to{
        before: =>
            @user = User\find @params.id
            @write status: 404, "Not Found" unless @user
        GET: => 
            render: true
        POST: =>
            @user\update{
                name: @params.name
                sex: @params.sex
                profession: @params.profession
                age: @params.age
                habits: @params.habits
                page: @params.page
                study: @params.study
                note: @params.note
            }
            render: true
  }

  [user_delete:"/user/delete/:id"]: respond_to{
        before: =>
            @user = User\find @params.id
            @write status: 404, "Not Found" unless @user
        GET: => 
            render: true
        POST: => 
            @user\delete!
            @users = User\select!
            render: "index"
  }
